package com.example.config;

import com.example.multidatasource.DynamicDataSource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源配置
 * @author long
 * @date 2024/9/3 20:39
 */
//@Configuration
public class DataSourceConfiguration {

    @Resource
    private Environment environment;

    @Bean
    public DynamicDataSource dataSource(){
        DynamicDataSource dataSource = new DynamicDataSource();
        dataSource.setDefaultTargetDataSource(defaultDataSource());

        Map<Object,Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("datasource",defaultDataSource());
        dataSourceMap.put("custom",customDataSource());
        dataSource.setTargetDataSources(dataSourceMap);
        return dataSource;
    }

    private DataSource defaultDataSource(){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name"));
        dataSource.setJdbcUrl(environment.getProperty("spring.datasource.url"));
        dataSource.setUsername(environment.getProperty("spring.datasource.username"));
        dataSource.setPassword(environment.getProperty("spring.datasource.password"));
        return dataSource;
    }

    private DataSource customDataSource(){
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(environment.getProperty("custom.datasource.driver-class-name"));
        dataSource.setJdbcUrl(environment.getProperty("custom.datasource.url"));
        dataSource.setUsername(environment.getProperty("custom.datasource.username"));
        dataSource.setPassword(environment.getProperty("custom.datasource.password"));
        return dataSource;
    }
}
